<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Edit information about you</title>
<script type="text/javascript" src="../../resources/js/jquery-1.6.js"></script>
<script type="text/javascript" src="../../resources/js/jquery.form.js"></script>
<script type="text/javascript" src="../../resources/js/jquery-validation-1.8.0/jquery.validate.js"></script>
<script type="text/javascript" src="../../resources/js/jquery-validation-1.8.0/additional-methods.js"></script>
<script type="text/javascript" src="../../resources/js/jquery-ui-1.8.11.custom.min.js"></script>
<script type="text/javascript" src="../../resources/js/jquery-ui-timepicker-addon.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="../../resources/css/start/jquery-ui-1.8.10.custom.css"/>
<style type="text/css">
    * {
        font-family: Verdana;
        font-size: 96%;
    }

    label {
        width: 10em;
        float: left;
    }

    label.error {
        float: none;
        color: red;
        padding-left: .5em;
        vertical-align: top;
    }

    p {
        clear: both;
    }

    .submit {
        margin-left: 50em;
    }

    em {
        font-weight: bold;
        padding-right: 1em;
        vertical-align: top;
    }

    body {
        font-size: 0.7em;
        font-weight: bold;
    }
</style>
<script type="text/javascript">
$(document).ready(function() {
    $("#cdateOfBirth").datepicker({
                dateFormat: "yy-mm-dd",
                changeMonth : true,
                changeYear : true
            });

    $("#editForm").validate({
                submitHandler: function(form) {
                    if (fileExist() && findSize() && checkFileExtension()){
                   $(form).ajaxSubmit({
                                        success: function(data) {
                                            if ($.parseJSON(data).isOk) {
                                                if (self!=top) {
                                                    window.parent.closeIframe(true);
                                                } else {
                                                    window.location="/workers/${worker.idUser}";
                                                }
                                            } else {
                                                alert("Данные не были изменены(((");
                                            }
                                        }
                                    })
                               }
                        },
                rules: {
                    firstName: {
                        required: true,
                        minlength: 2,
                        maxlength: 24
                    },
                    lastName: {
                        required: true,
                        minlength: 2,
                        maxlength: 24
                    },
                    dateOfBirth: {
                        required:true
                    },
                    city: {
                        min: 1,
                        required: true,
                        //remote: "validation/checkCity"
                    },
                    sex: {
                        required: true
                    },
                    jobTypes: {
                        required: true
                    },
                    about: {
                        required: true
                    }
                },
                messages: {
                    firstName: {
                                required: "Это поле обязательно для заполнения",
                                minlength: "Минимальная длинна имени - 2 символа",
                                maxlength: "Максимальная длинна имени - 24 символа"
                            },
                            lastName: {
                                required: "Это поле обязательно для заполнения",
                                minlength: "Минимальная длинна фамилии - 2 символа",
                                maxlength: "Максимальная длинна фамилии - 24 символа",
                            },
                         dateOfBirth: {
                                                    required: "Это поле обязательно для заполнения"
                                                },

                    city: {
                                min: "К сожалению, такого города нет в нашей базе данных",
                                required: "Это поле обязательно для заполнения",
                                remote: "К сожалению, такого города нет в нашей базе данных"
                            },
                            jobTypes: {
                                required: "Это поле обязательно для заполнения"
                            },
                             sex: {
                            required: "Выберите пожалуйста пол"
                        },
                        about: {
                            required: "Это поле обязательно для заполнения"
                        }
                }
            });

    $("#ccity").autocomplete({
                source: function(request, response) {
                    jQuery.ajax({
                                url : "/search/cities",
                                dataType : "json",
                                data : {
                                    term : request.term
                                    //groupId : $("#groupId").val();
                                },
                                success : function(data) {
                                    response(jQuery.map(data, function(item) {
                                        return {
                                            label: item.ruName,
                                            value: item.ruName,
                                            id: item.idCity
                                        }
                                    }))
                                }
                            })
                },
                select: function(event, ui) {
                    if (ui.item) {
                        putCityId(ui.item.id);
                    }
                },
                minLength : 2,
                open : function() {
                    $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
                },
                close: function() {
                    $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
                }
            });

    $(".invisible").hide();

    $(".checkButton").button();

    $(".submit").button();

    $(".checkButton").click(function() {
        //$(this).find(".timeChooser").show();
        //return false;
        if ($(this).val() == "добавить") {
            $(this).val("удалить");
            $(this).next().children().val("");
        } else {
            $(this).val("check");
        }
        $(this).next().toggle('slow');
    });

    $(".timeClass").timepicker({
                showSecond: false,
                timeFormat: 'hh:mm:ss',
                onClose: function(e) {
                    var startTime, endTime;
                    if ($(this).attr('name').indexOf('start') >= 0) {
                        startTime = $(this);
                        endTime = $(this.nextElementSibling);
                    }
                    if ($(this).attr('name').indexOf('end') >= 0) {
                        endTime = $(this);
                        startTime = $(this.previousElementSibling);
                    }

                    if (startTime.val().trim() != "" && endTime.val().trim() != "" && startTime.val() > endTime.val()) {
                        //endTime.css('background-color','red');
                        endTime.val(startTime.val());
                    }

                }

            });

    $("#weekdaysTabs").tabs({
                collapsible: true,
                selected: -1
            });


    $("#checkbox").buttonset();

  //  $("#radiosex").buttonset();

    $("#dialog:ui-dialog").dialog("destroy");

    var oldpass = $("#oldpass"),
            newpass = $("#newpass"),
            confirmpass = $("#confirmpass"),
            allFields = $([]).add(oldpass).add(newpass).add(confirmpass),
            tips = $(".validateTips");

    function updateTips(t) {
        tips
                .text(t)
                .addClass("ui-state-highlight");
        setTimeout(function() {
            tips.removeClass("ui-state-highlight", 1500);
        }, 500);
    }

    function checkLength(o, n, min, max) {
        if (o.val().length > max || o.val().length < min) {
            o.addClass("ui-state-error");
            updateTips("Length of " + n + " must be between " +
                    min + " and " + max + ".");
            return false;
        } else {
            return true;
        }
    }

    function checkRegexp(o, regexp, n) {
        if (!( regexp.test(o.val()) )) {
            o.addClass("ui-state-error");
            updateTips(n);
            return false;
        } else {
            return true;
        }
    }

    $("#dialog-form").dialog({
                autoOpen: false,
                height: 300,
                width: 350,
                modal: true,
                buttons: {
                    "Change": function() {
                        var bValid = true;
                        allFields.removeClass("ui-state-error");

                        bValid = bValid && checkLength(oldpass, "old password", 6, 12);
                        bValid = bValid && checkLength(newpass, "new password", 6, 12);
                        bValid = bValid && checkLength(confirmpass, "confirm password", 6, 12);

                        // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                        bValid = bValid && checkRegexp(newpass, /^([0-9a-zA-Z])+$/, "Password field only allow : a-Z 0-9");
                        bValid = bValid && checkRegexp(confirmpass, /^([0-9a-zA-Z])+$/, "Password field only allow : a-Z 0-9");

                        bValid = bValid && newpass.val() == confirmpass.val();
                        if (newpass.val() != confirmpass.val()) {
                            newpass.addClass("ui-state-error");
                            updateTips("New password does not match the confirmation");
                        }

                        if (bValid) {
                            $.getJSON('/validation/changePassword',
                                    {oldpass:oldpass.val(),
                                        newpass:newpass.val(),
                                        confirmpass:confirmpass.val()
                                    },
                                    function(data) {
                                        if (data.isOk) {
                                            $("#dialog-form").dialog("close");
                                        } else {
                                            oldpass.addClass("ui-state-error");
                                            updateTips(data.message);
                                        }
                                    })

                        }
                    },
                    Cancel: function() {
                        $(this).dialog("close");
                    }
                },
                close: function() {
                    allFields.val("").removeClass("ui-state-error");
                }
            });

    $("#change-password")
            .button()
            .click(function() {
                $("#dialog-form").dialog("open");
            });


});

function putCityId(idCity) {
    $("#idCity").val(idCity);
}

    function findSize() {
    if ( $.browser.msie ) {
       var a = document.getElementById('cimage').value;
           $('#myImage').attr('src',a);
           var imgbytes = document.getElementById('myImage').fileSize;
           //var imgkbytes = Math.round(parseInt(imgbytes)/1024);
           if (imgbytes>100000) {
           alert("Размер фотографии превышает 100кб. Добавьте пожалуйста фотографию с меньшим размером!");
                   return false; }
                   else {return true;}
    }else {
           var fileInput = $("#cimage")[0];
           var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
           //var imgkbytes = Math.round(parseInt(imgbytes)/1024);
           if (imgbytes>100000) {
           alert("Размер фотографии превышает 100кб. Добавьте пожалуйста фотографию с меньшим размером!");
                   return false; }
                   else {return true;}
     }
}

function checkFileExtension(){
     var filename;

      if ( $.browser.msie ) {
      filename =  document.getElementById('cimage').value;

    }else {
           var fileInput = $("#cimage")[0];
           filename =  fileInput.value;

     }

    var ext = filename.split('.').pop();
    if((ext!="jpg") && (ext!="jpeg")) {
        alert("Допустимы фотографии только в формате jpg!");
        return false;
    }
    return true;
}

function fileExist(){
       if ( $.browser.msie ) {
       var a = document.getElementById('cimage').value;
           $('#myImage').attr('src',a);
           return document.getElementById('myImage').fileSize;


    }else {
           var fileInput = $("#cimage")[0];
           return fileInput.files[0].fileSize; // Size returned in bytes.

     }

}

</script>

</head>
<body>

<div id="dialog-form" title="Change password">
    <p class="validateTips">All form fields are required.</p>

    <form>
        <fieldset>
            <label for="oldpass">Old password</label>
            <input type="password" name="old" id="oldpass" class="text ui-widget-content ui-corner-all"/>
            <label for="newpass">New password</label>
            <input type="password" name="newpass" id="newpass" value="" class="text ui-widget-content ui-corner-all"/>
            <label for="confirmpass">Confirm password</label>
            <input type="password" name="confirmpass" id="confirmpass" value=""
                   class="text ui-widget-content ui-corner-all"/>
        </fieldset>
    </form>
</div>

<sf:form modelAttribute="worker" class="cmxform" id="editForm" method="post" action="/saveEditedWorker"
         enctype="multipart/form-data">
<fieldset>
<!--<legend>Editing of your personal information</legend>-->

<sf:input path="idUser" hidden="hidden"/>
<p>
    <label for="cemail">E-Mail</label>
    <em></em><input id="cemail" size="25" name="email" value="${worker.email}" readonly="readonly" disabled="disabled" />
    <sf:input hidden="hidden" path="email" id="cemail" size="25" name="email" readonly="readonly" disabled="disabled" />
</p>

<input type="button" id="change-password" value="Change password"/>

<p>
    <label for="cfirstName">Имя *</label>
    <em></em><sf:input path="firstName" id="cfirstName" name="firstName" size="25" class="required"/>
</p>

<p>
    <label for="clastName">Фамилия *</label>
    <em></em><sf:input path="lastName" id="clastName" name="lastName" size="25" class="required"/>
</p>

<p>
    <label for="ccity">Город *</label>
    <em></em><input id="ccity" title="Начните печатать название города и выберите Ваш город из выпавшего списка."
     name="visicity" value="${worker.city.ruName }" size="25" class="required"/>
    <sf:input path="city" value="${worker.city.idCity }" id="idCity" type="hidden" name="city"/>
</p>

<p>
    <img id="myImage" src="" style="display:none;"><br>
    <label for="cimage">Фотография</label>
    <img alt="avatar" src="/workers/${worker.idUser}/getImage"/>
    <input type="file" id="cimage" name="file" size="25"/>
</p>


<p>
    <label for="cdateOfBirth">Дата рождения *</label>
    <em></em><sf:input path="dateOfBirth" id="cdateOfBirth" name="dateOfBirth" size="25" readonly="readonly"/>
</p>

<p>

<div id="radiosex">
    <label for="csex">Пол *<em></em></label>
        <%--<c:choose>--%>
        <%--<c:when test="${worker.sex == 1 }">--%>
        <%--<input type="radio" id="radiosex1" name="sex" value="1" checked="checked" class="required"/>--%>
        <%--<label for="radiosex1">male</label>--%>
        <%--<input type="radio" id="radiosex2" name="sex" value="0" class="required"/>--%>
        <%--<label for="radiosex2">female</label>--%>
        <%--</c:when>--%>
        <%--<c:otherwise>--%>
        <%--<input type="radio" id="radiosex1" name="sex" value="1" class="required"/>--%>
        <%--<label for="radiosex1">male</label>--%>
        <%--<input type="radio" id="radiosex2" name="sex" value="0" checked="checked" class="required"/>--%>
        <%--<label for="radiosex2">female</label>--%>
        <%--</c:otherwise>--%>
        <%--</c:choose>--%>
    М: <sf:radiobutton type="radio" id="radiosex1" path="sex" name="sex" value="1"/>
    Ж: <sf:radiobutton type="radio" id="radiosex2" path="sex" name="sex" value="0"/>
</div>
</p>

<p>
    <label for="cphone">Телефон </label>
    <em></em><sf:input path="phone" id="cphone" name="phone" size="25"/>
</p>

<p>
    <label for="cskype">Skype  </label>
    <em></em><sf:input path="skype" id="cskype" name="skype" size="25"/>
</p>

<p>
    <label for="cicq">Icq  </label>
    <em></em><sf:input id="cicq" path="icq" name="icq" size="25"/>
</p>

Предпочитаемое время для работы
<div id="weekdaysTabs">

<ul>
    <li><a href="#mondayTab">Понедельник</a></li>
                <li><a href="#tuesdayTab">Вторник</a></li>
                <li><a href="#wednesdayTab">Среда</a></li>
                <li><a href="#thursdayTab">Четверг</a></li>
                <li><a href="#fridayTab">Пятница</a></li>
                <li><a href="#saturdayTab">Суббота</a></li>
                <li><a href="#sundayTab">Воскресение</a></li>
</ul>

<div id="mondayTab">
    <p>

        <c:choose>
            <c:when test="${monday !=null }">
                <input class="checkButton" type="button" value="удалить"/>
			<span class="timeChooser">
            
                                		Начало:<input class="timeClass" type="text" value="${monday.startTime }"
                                                          readonly="readonly"
                                                          name="startTime0"/>
                                		Конец:<input class="timeClass" type="text" value="${monday.endTime }"
                                                        readonly="readonly"
                                                        name="endTime0"/>
                                                </span>
            </c:when>
            <c:otherwise>
                <input class="checkButton" type="button" value="добавить"/>
			<span class="timeChooser invisible">
                                		Начало:<input class="timeClass" type="text" value="" readonly="readonly"
                                                          name="startTime0"/>
                                		Конец:<input class="timeClass" type="text" value="" readonly="readonly"
                                                        name="endTime0"/>
            </span>
            </c:otherwise>
        </c:choose>


    </p>
</div>
<div id="tuesdayTab">
    <p>

        <c:choose>

            <c:when test="${tuesday !=null }">
                <input class="checkButton" type="button" value="удалить"/>
			<span class="timeChooser">
                                		Начало:<input class="timeClass" type="text" value="${tuesday.startTime }"
                                                          readonly="readonly"
                                                          name="startTime1"/>
                                		Конец:<input class="timeClass" type="text" value="${tuesday.endTime }"
                                                        readonly="readonly"
                                                        name="endTime1"/>
                                                </span>
            </c:when>
            <c:otherwise>
                <input class="checkButton" type="button" value="добавить"/>
			<span class="timeChooser invisible">
                                		Начало:<input class="timeClass" type="text" value="" readonly="readonly"
                                                          name="startTime1"/>
                                		Конец:<input class="timeClass" type="text" value="" readonly="readonly"
                                                        name="endTime1"/>
                                                </span>
            </c:otherwise>
        </c:choose>
        </span>
    </p>
</div>

<div id="wednesdayTab">
    <p>
        <c:choose>
            <c:when test="${wednesday !=null }">

                <input class="checkButton" type="button" value="удалить"/>
			<span class="timeChooser">
			Начало:<input class="timeClass" type="text" value="${wednesday.startTime }" readonly="readonly"
                              name="startTime2"/>
                                		Конец:<input class="timeClass" type="text" value="${wednesday.endTime }"
                                                        readonly="readonly"
                                                        name="endTime2"/>
                                                </span>
            </c:when>
            <c:otherwise>
                <input class="checkButton" type="button" value="добавить"/>
			<span class="timeChooser invisible">
                                		Начало:<input class="timeClass" type="text" value="" readonly="readonly"
                                                          name="startTime2"/>
                                		Конец:<input class="timeClass" type="text" value="" readonly="readonly"
                                                        name="endTime2"/>
                                                </span>
            </c:otherwise>
        </c:choose>
        </span>
    </p>
</div>
<div id="thursdayTab">
    <p>

        <c:choose>
            <c:when test="${thursday !=null }">
                <input class="checkButton" type="button" value="удалить"/>
			<span class="timeChooser">
                                		Начало:<input class="timeClass" type="text" value="${thursday.startTime }"
                                                          readonly="readonly"
                                                          name="startTime3"/>
                                		Конец:<input class="timeClass" type="text" value="${thursday.endTime }"
                                                        readonly="readonly"
                                                        name="endTime3"/>
                                               </span>
            </c:when>
            <c:otherwise>
                <input class="checkButton" type="button" value="добавить"/>
			<span class="timeChooser invisible">
                                		Начало:<input class="timeClass" type="text" value="" readonly="readonly"
                                                          name="startTime3"/>
                                		Конец:<input class="timeClass" type="text" value="" readonly="readonly"
                                                        name="endTime3"/>
                                                </span>
            </c:otherwise>
        </c:choose>
        </span>
    </p>
</div>
<div id="fridayTab">
    <p>
        <c:choose>
            <c:when test="${friday !=null }">
                <input class="checkButton" type="button" value="удалить"/>
			<span class="timeChooser">
                                		Начало:<input class="timeClass" type="text" value="${friday.startTime }"
                                                          readonly="readonly"
                                                          name="startTime4"/>
                                		Конец:<input class="timeClass" type="text" value="${friday.endTime }"
                                                        readonly="readonly"
                                                        name="endTime4"/>
                                                </span>
            </c:when>
            <c:otherwise>
                <input class="checkButton" type="button" value="добавить"/>
			<span class="timeChooser invisible">
                                		Начало:<input class="timeClass" type="text" value="" readonly="readonly"
                                                          name="startTime4"/>
                                		Конец:<input class="timeClass" type="text" value="" readonly="readonly"
                                                        name="endTime4"/>
                                                </span>
            </c:otherwise>
        </c:choose>
        </span>
    </p>
</div>
<div id="saturdayTab">
    <p>

        <c:choose>
            <c:when test="${saturday !=null }">
                <input class="checkButton" type="button" value="удалить"/>
			<span class="timeChooser">
                                		Начало:<input class="timeClass" type="text" value="${saturday.startTime }"
                                                          readonly="readonly"
                                                          name="startTime5"/>
                                		Конец:<input class="timeClass" type="text" value="${saturday.endTime }"
                                                        readonly="readonly"
                                                        name="endTime5"/>
                                                </span>
            </c:when>
            <c:otherwise>
                <input class="checkButton" type="button" value="добавить"/>
			<span class="timeChooser invisible">
                                		Начало:<input class="timeClass" type="text" value="" readonly="readonly"
                                                          name="startTime5"/>
                                		Конец:<input class="timeClass" type="text" value="" readonly="readonly"
                                                        name="endTime5"/>
                                                </span>
            </c:otherwise>
        </c:choose>
        </span>
    </p>
</div>
<div id="sundayTab">
    <p>
        <c:choose>
            <c:when test="${sunday !=null }">
                <input class="checkButton" type="button" value="удалить"/>
			<span class="timeChooser">
                                		Начало:<input class="timeClass" type="text" value="${sunday.startTime }"
                                                          readonly="readonly"
                                                          name="startTime6"/>
                                		Конец:<input class="timeClass" type="text" value="${sunday.endTime }"
                                                        readonly="readonly"
                                                        name="endTime6"/>
                                                </span>
            </c:when>
            <c:otherwise>
                <input class="checkButton" type="button" value="добавить"/>
			<span class="timeChooser invisible">
                                		Начало:<input class="timeClass" type="text" value="" readonly="readonly"
                                                          name="startTime6"/>
                                		Конец:<input class="timeClass" type="text" value="" readonly="readonly"
                                                        name="endTime6"/>
                                                </span>
            </c:otherwise>
        </c:choose>
        </span>
    </p>
</div>
</div>


<p>
    <label for="cabout">О себе *</label>
    <em></em><sf:textarea path="about" id="cabout" name="about"/>
</p>

<p>
    <label for="cjobTypesEnd">Предпочитаемый тип работ *</label>
    <em></em>

<div id="checkbox">
    <c:forEach var="workersJobType" items="${workersJobTypes}">
        <sf:input path="jobTypes" id="jobTypes${workersJobType.idJob }" type="checkbox" name="jobTypes" checked="true"
               value="${workersJobType.idJob}" class="required"/>
        <label for="jobTypes${workersJobType.idJob }">${workersJobType.title}</label>
    </c:forEach>
    <c:forEach var="jobType" items="${jobTypes}">
        <sf:input path="jobTypes" id="jobTypes${jobType.idJob }" type="checkbox" name="jobTypes" value="${jobType.idJob}"
               class="required"/>
        <label for="jobTypes${jobType.idJob }">${jobType.title}</label>
    </c:forEach>

    <input id="cjobTypesEnd" type="hidden"/>
</div>
</p>
<br/>

<input align="right" class="submit" type="submit" value="Изменить"/>

</fieldset>
</sf:form>
</body>
</html>